package com.sto.stoapp.activity.administrator.system;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.adapter.BluePairAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.listener.StoOnItemClickListener;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.Action;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("HandlerLeak")
public class SystemBlueWeigthSettingActivity extends StoListenerActivity {

	private TextView weighTestView;

	private Button scalesSpinner, decimalPlacesSpinner;

	private Button weighTestButton, searchBlue;

	private EditText blueAddress;

	// 蓝牙适配器
	private BluetoothAdapter mBTAdapter;

	private BlueReadThread blueReadThread;

	private void isMacInvalid(String code) {
		if (StoFilePreference.getInstance(this).getSelectedScalesControl()
				.equals(getText(R.string.select_empty_type))) {
			weighTestView.setText(R.string.please_select_scales_first);
			return;
		}
		try {
			// mac地址长度为12位
			if (code.length() != 12) {
				Helper.showToast(this, getText(R.string.mac_address_invalid)
						.toString());
				SoundManager.getInstance(this).playFailureSound();
				return;
			}
			String[] str = new String[6];
			for (int i = 0; i < 6; i++) {
				str[i] = code.substring(i * 2, i * 2 + 2);
			}
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < 6; i++) {
				if (i != 5) {
					sb.append(str[i]).append(":");
				} else {
					sb.append(str[i]);
				}
			}
			blueAddress.setText(sb.toString());
			SoundManager.getInstance(this).playSuccessSound();
			if (blueReadThread != null) {
				blueReadThread.cancelDialog();
				blueReadThread.clearBlueDevices();
				blueReadThread = null;
			}
			weighTestView.setText("");
			blueConnectPair(sb.toString().toUpperCase());
			/*
			 * blueReadThread = new BlueReadThread(this, blueHandler,
			 * sb.toString(), false); blueReadThread.start();
			 */
			// weighTestView.setText(getString(R.string.now_connect_blue));
			StoFilePreference.getInstance(this).setBluetoothMacAddress(
					sb.toString().toUpperCase());
		} catch (Exception e) {
			weighTestView.setText(R.string.mac_address_parse_failure);
		}

	}

	/**
	 * 配对蓝牙
	 */
	private void blueConnectPair(String address) {
		try {
			if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {

				final BluetoothDevice btDev = BluetoothAdapter
						.getDefaultAdapter().getRemoteDevice(address);
				if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
					// 利用反射方法调用BluetoothDevice.createBond(BluetoothDevice
					// remoteDevice);
					Helper.showSoundToast(SystemBlueWeigthSettingActivity.this,
							"正在蓝牙配对...", false);
					/*
					 * Method createBondMethod = BluetoothDevice.class
					 * .getMethod("createBond"); createBondMethod.invoke(btDev);
					 */
					weighTestView.setText("正在蓝牙配对...");
					blueReadThread = new BlueReadThread(this, blueHandler,
							address, false);
					blueReadThread.start();

				} else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) {
					// Helper.showSoundToast(SystemBlueWeigthSettingActivity.this,"蓝牙已配对",false);
					Helper.showSoundToast(SystemBlueWeigthSettingActivity.this,
							"蓝牙正在连接...", false);
					/*
					 * Method createBondMethod = BluetoothDevice.class
					 * .getMethod("createBond"); createBondMethod.invoke(btDev);
					 */
					weighTestView.setText("蓝牙正在连接...");
					blueReadThread = new BlueReadThread(this, blueHandler,
							address, false);
					blueReadThread.start();
				} else {

				}
			} else {
				SoundManager.getInstance(this).playFailureSound();
				weighTestView.setText(R.string.blue_no_open);
			}
		} catch (Exception e) {
			SoundManager.getInstance(this).playFailureSound();
			// Helper.showToastSound(SystemBlueWeigthSettingActivity.this,
			// getText(R.string.blue_address_error).toString(), false);
			e.printStackTrace();
			weighTestView.setText(R.string.mac_address_parse_failure);
		}
	}

	// 显示蓝牙重量
	private Handler blueHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
					if (msg.obj != null && !msg.obj.toString().equals("")) {
						String result = msg.obj.toString();
						Log.d("ge", String.valueOf(result));

						// 表示连接蓝牙失败
						if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
							// setViewEnabled(true);
							weighTestView.setText(R.string.blue_connect_fail);
						}
						// 没有选择秤型号
						else if (result
								.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
							// setViewEnabled(true);
							weighTestView
									.setText(R.string.no_select_scales_model);
						}
						// 读取数据失败
						else if (result.equals(BlueWeigthManager.READ_ERROR)) {
							// setViewEnabled(true);
							weighTestView.setText(R.string.get_data_error);
						} else {
							// 显示重量
							// setViewEnabled(false);
							weighTestView
									.setText(getString(R.string.blue_weight)
											+ result);
						}
					}
				}
				// else if (msg.what == BlueConnectThread.NOW_CONNECT_BLUE) {
				// weighTestView.setText(R.string.now_connect_blue);
				// } else if (BlueConnectThread.BLUE_NOT_PAIR == msg.what) {
				// weighTestView.setText(R.string.blue_no_pair);
				// }
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.admin_blue_weight_control);
		String broadType = getIntent().getStringExtra("busiType");
		// 判断是管理员的系统设置还是业务内部的系统设置
		if (broadType != null && !broadType.equals("")) {
			this.setTitleBottom(R.string.blue_settings, broadType);
		} else {
			this.setTitleBottom(R.string.blue_settings,
					HomeBroadAction.ADMINISTRATOR_BROAD);
		}
		initWidget();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mBTAdapter == null) {
			mBTAdapter = BluetoothAdapter.getDefaultAdapter();
		}
	}

	private void selectBlueAdapter() {
		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				final List<BluetoothDevice> devicesList = new ArrayList<BluetoothDevice>(
						mBTAdapter.getBondedDevices());
				if (devicesList.size() > 0) {
					View view = LayoutInflater.from(this).inflate(
							R.layout.blue_devices_dialog, null);
					ListView blueList = (ListView) view
							.findViewById(R.id.blue_pair_list);
					blueList.setAdapter(new BluePairAdapter(this, devicesList));
					Button cancel = (Button) view.findViewById(R.id.cancel);
					final BaseDialog dialog = new BaseDialog(this);
					dialog.showLog(view);
					cancel.setOnClickListener(new StoOnClickListener(this) {

						@Override
						public void mHonClick(View view) {
							dialog.dismiss();
						}
					});
					blueList.setOnItemClickListener(new StoOnItemClickListener(
							this) {

						@Override
						public void KcOnItemClickListener(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							dialog.dismiss();
							if (blueReadThread != null) {
								blueReadThread.clearBlueDevices();
								blueReadThread = null;
							}
							if (StoFilePreference
									.getInstance(
											SystemBlueWeigthSettingActivity.this)
									.getSelectedScalesControl()
									.equals(getText(R.string.select_empty_type))) {
								weighTestView
										.setText(R.string.please_select_scales_first);
								return;
							}
							// setViewEnabled(false);
							StoFilePreference.getInstance(
									SystemBlueWeigthSettingActivity.this)
									.setBluetoothMacAddress(
											devicesList.get(arg2).getAddress());
							blueReadThread = new BlueReadThread(
									SystemBlueWeigthSettingActivity.this,
									blueHandler, devicesList.get(arg2)
											.getAddress(), false);
							blueReadThread.start();
							weighTestView
									.setText(getString(R.string.now_connect_blue));
						}
					});
				} else {
					weighTestView.setText(R.string.no_selected_scales);
				}
			} else {
				weighTestView.setText(R.string.blue_no_open);
			}
		} else {
			weighTestView.setText(R.string.blue_not_available);
		}
	}

	private void setViewEnabled(boolean enabled) {
		scalesSpinner.setEnabled(enabled);
		decimalPlacesSpinner.setEnabled(enabled);
		weighTestButton.setEnabled(enabled);
	}

	// 初始化控件
	private void initWidget() {
		blueAddress = (EditText) this.findViewById(R.id.blue_address);
		blueAddress.setInputType(InputType.TYPE_NULL);
		weighTestView = (TextView) this.findViewById(R.id.weigh_test_view);
		weighTestButton = (Button) this.findViewById(R.id.weigh_test_button);
		weighTestButton.setOnClickListener(listener);
		searchBlue = (Button) this.findViewById(R.id.search_blue);
		searchBlue.setOnClickListener(listener);
		// 秤的类型
		scalesSpinner = (Button) this.findViewById(R.id.scales_spinner);

		// 小数点精度
		decimalPlacesSpinner = (Button) this
				.findViewById(R.id.decimal_places_spinner);
		scalesSpinner.setText(StoFilePreference.getInstance(this)
				.getSelectedScalesControl());
		decimalPlacesSpinner.setText(StoFilePreference.getInstance(this)
				.getSelectedDecimalPlacesControl());
		scalesSpinner.setOnClickListener(listener);
		decimalPlacesSpinner.setOnClickListener(listener);
		setBluetoothCloseOpenListener(new BluetoothCloseOpenListener() {

			@Override
			public void listener() {
				closeBluetooth();
				new CloseThread().start();

			}
		});
	}

	StoOnClickListener listener = new StoOnClickListener(this) {

		@Override
		public void mHonClick(View view) {
			switch (view.getId()) {
			case R.id.scales_spinner:
				selectSalesType();
				break;
			case R.id.decimal_places_spinner:
				selectDecimalType();
				break;
			case R.id.weigh_test_button:
				selectBlueAdapter();
				break;
			case R.id.search_blue:
				Intent intent = new Intent();
				intent.setAction(Action.BLUETOOTH_ACTION);
				startActivity(intent);
				break;
			default:
				break;
			}
		}
	};

	private void selectSalesType() {
		new AlertDialog.Builder(this)
				.setTitle(R.string.select_scales_type)
				.setItems(R.array.sales_type,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								String[] salesTypes = getResources()
										.getStringArray(R.array.sales_type);
								scalesSpinner.setText(salesTypes[arg1]);
								StoFilePreference.getInstance(
										SystemBlueWeigthSettingActivity.this)
										.setSelectedScalesControl(
												salesTypes[arg1]);
							}
						}).show();
	}

	private void selectDecimalType() {
		new AlertDialog.Builder(this)
				.setTitle(R.string.scales_decimal_places)
				.setItems(R.array.decimal_type,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								String[] decimalTypes = getResources()
										.getStringArray(R.array.decimal_type);
								decimalPlacesSpinner
										.setText(decimalTypes[arg1]);
								StoFilePreference.getInstance(
										SystemBlueWeigthSettingActivity.this)
										.setSelectedDecimalPlacesControl(
												decimalTypes[arg1]);
							}
						}).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				if (blueReadThread != null) {
					blueReadThread.clearBlueDevices();
					mBTAdapter.cancelDiscovery();
					blueReadThread = null;
				}
			}
		}

		blueHandler.removeMessages(BlueWeigthManager.UPDATE_BLUE_DATA);

	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String code = scanData;
			isMacInvalid(code);
		}

	}

	// @Override
	// public void onBackPressed() {
	// // TODO Auto-generated method stub
	// super.onBackPressed();
	// doBack();
	// }
	//
	// @Override
	// protected void doBack() {
	// if (BluetoothAdapter.getDefaultAdapter().isEnabled()
	// && blueReadThread != null && !blueReadThread.isConnected()) {
	// handler.sendEmptyMessageAtTime(5, 5000);
	// showDialog();
	// } else {
	// super.doBack();
	// }
	// }
}
